package tools;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class ColorConversions {
	
	/**
	 * Berechnet das Helligkeitsbild von einem RGBbild
	 * 
	 * @param rgb eingabebild als integer array der laenge n*m
	 * @param fillme ausgabebild als integer array 
	 * @return fillme ausgabebild als integer array
	 * 
	 */
	public static int[] getFastLuminance(int[] rgb, int[] fillme) {
		for (int i = 0; i<rgb.length; i++) {
			int temp = rgb[i], r = (temp>>16)&0xFF, g = (temp>>8)&0xFF, b = temp&0xFF;
			fillme[i] = (r*77+g*151+b*28)>>8;
		}
		return fillme;
	}

	public static int[] buildRGB(int[] r, int[] g, int[] b, int[] fillme) {
		for (int i = 0; i<r.length; i++) {
			fillme[i] = r[i]<<16 | g[i]<<8 | b[i] | 0xFF000000;
		}
		return fillme;
	}
	public static void main(String[] args) {
		try {
			JFrame ff = new JFrame();
			ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			final BufferedImage bi = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("res/test2.png"));
			
			JComponent canvas = new JComponent() {
				{setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));}
				@Override
				public void paint(Graphics g) {
					g.drawImage(bi, 0, 0, this);
					super.paint(g);
				}
			};
			
			int[] grey = new int[bi.getWidth()*bi.getHeight()];
			int[] pixels = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), new int[bi.getWidth()*bi.getHeight()], 0, bi.getWidth());
			grey = ColorConversions.getFastLuminance(pixels, grey);
			
			pixels = ColorConversions.buildRGB(grey, grey, grey, pixels);
			bi.setRGB(0, 0, bi.getWidth(), bi.getHeight(), pixels, 0, bi.getWidth());
			
			ff.add(canvas);
			ff.pack();
			ff.setVisible(true);
		
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
